<?php
/*******************************************************************
 * [JishiGou] (C)2005 - 2099 Cenwor Inc.
 *
 * This is NOT a freeware, use is subject to license terms
 *
 * @Filename channel.logic.php $
 *
 * @Author http://www.jishigou.net $
 *
 * @Date 2013-04-26 08:42:17 1195736293 1559961713 20383 $
 *******************************************************************/




if(!defined('IN_JISHIGOU')) {
    exit('invalid request');
}

class ChannelLogic
{

	function ChannelLogic()
	{

	}

	
	function is_exists($ch_id = 0)
	{
		$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
		return $count > 0 ? true : false;
	}
	
	function have_child($ch_id = 0)
	{
		$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('channel')." WHERE parent_id='{$ch_id}'");
		return $count > 0 ? true : false;
	}

	
	function can_pub_topic($ch_id)
	{
		$return = false;
		$is_channel = $this->is_exists($ch_id);
		if($is_channel){
			global $_J;
			$purview = DB::result_first("SELECT purview FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
			if(empty($purview) || in_array($_J['member']['role_id'],explode(',',$purview))){
				$return = true;
			}
		}
		return $return;
	}

	
	function verify_pub_topic($ch_id)
	{
		$return = false;
		$is_channel = $this->is_exists($ch_id);
		if($is_channel){
			global $_J;
			$val = DB::fetch_first("SELECT `verify`,`filter` FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
			if($val['verify'] && !in_array($_J['member']['role_id'],explode(',',$val['filter']))){
				$return = true;
			}
		}
		return $return;
	}

	
	function id2subject($ch_id)
	{
		static $channelname;
		if($channelname[$ch_id]){
			$subject = $channelname[$ch_id];
		}else{
			$subject = DB::result_first("SELECT ch_name FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}' ");
			$channelname[$ch_id] = $subject;
		}
		return $subject;
	}

	
	function mychannel($uid = MEMBER_ID)
	{
		$channels = array();
		$uid = $uid ? $uid : MEMBER_ID;
		$query = DB::query("SELECT bc.ch_id,c.ch_name,c.topic_num,c.total_topic_num FROM ".DB::table('buddy_channel')." bc LEFT JOIN ".DB::table('channel')." c ON bc.ch_id=c.ch_id where bc.uid='$uid'");
		while ($value = DB::fetch($query))
		{
			$value['topicnum'] = $value['total_topic_num'] > $value['topicnum'] ? $value['total_topic_num'] : $value['topicnum'];
			$value['buddy_mumbers'] = $this->getChannelBuddyUserNums($value['ch_id']);
			$channels[$value['ch_id']] = $value;
		}
		return $channels;
	}

	
	function category_exists($ch_name, $pid = 0)
	{
		$count = DB::result_first("SELECT COUNT(*)
								   FROM ".DB::table('channel')."
								   WHERE ch_name='{$ch_name}' AND parent_id='{$pid}'");
		return $count > 0 ? true : false;
	}

	
	function id2category($ch_id)
	{
		$channel = array();
		$channel = DB::fetch_first("SELECT * FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
		return $channel;
	}

	
	function &get_category_tree($dotree=0)
	{
		$tree = $cat_ary = $indextree = array();
		$query = DB::query("SELECT *
							FROM ".DB::table('channel')."
							ORDER BY display_order ASC");
		while ($value = DB::fetch($query)) {
			$cat_ary[] = $value;
			$indextree[$value['ch_id']]['id'] = $value['ch_id'];
			$indextree[$value['ch_id']]['name'] = $value['ch_name'];
			$indextree[$value['ch_id']]['picture'] = $value['picture'] ? str_replace('./','/',$value['picture']) : "/images/channelimg.gif";
		}

		if (!empty($cat_ary)) {
			if($dotree){
				$tree = $indextree;
			}else{
				$tree = $this->category_tree($cat_ary);
			}
		}
		return $tree;
	}

	
	function update_data()
	{
		$query = DB::query("SELECT * FROM ".DB::table('channel')." ORDER BY parent_id DESC");
		while ($value = DB::fetch($query)) {
			$totala = DB::result_first("SELECT COUNT(*) FROM ".DB::table('topic')." WHERE item = 'channel' AND item_id = '{$value['ch_id']}'");
			DB::query("UPDATE ".DB::table('channel')." SET total_topic_num={$totala},topic_num={$totala} WHERE ch_id='{$value['ch_id']}'");
			if($value['parent_id'] == 0){
				$total = DB::result_first("SELECT SUM(topic_num) FROM ".DB::table('channel')." WHERE parent_id = '{$value['ch_id']}'");
				if($total > 0){
					DB::query("UPDATE ".DB::table('channel')." SET total_topic_num=total_topic_num+{$total} WHERE ch_id='{$value['ch_id']}'");
				}
			}
		}
		$this->update_category_cache();
	}

	
	function move_channel($from_id=0,$to_id=0,$cutc=0)
	{
		if($from_id > 0 && $to_id > 0 && $from_id != $to_id){
			$from_info = $this->id2category($from_id);
			if($from_info['topic_num']>0){
				$to_info = $this->id2category($to_id);
				DB::query("UPDATE ".DB::table('topic')." SET item_id={$to_id} WHERE item = 'channel' AND item_id='{$from_id}'");
				DB::query("UPDATE ".DB::table('buddy_channel')." SET ch_id={$to_id} WHERE ch_id='{$from_id}'");
								DB::query("UPDATE ".DB::table('topic_recommend')." SET item_id={$to_id} WHERE item = 'channel' AND item_id='{$from_id}'");
				DB::query("UPDATE ".DB::table('channel')." SET total_topic_num=total_topic_num+{$from_info['total_topic_num']},topic_num=topic_num+{$from_info['topic_num']} WHERE ch_id = '{$to_id}'");
				DB::query("UPDATE ".DB::table('channel')." SET total_topic_num=0,topic_num=0 WHERE ch_id = '{$from_id}'");
				if($from_info['parent_id'] != $to_info['parent_id']){
					if($from_info['parent_id'] > 0){						DB::query("UPDATE ".DB::table('channel')." SET total_topic_num=total_topic_num-{$from_info['total_topic_num']} WHERE ch_id = '".$from_info['parent_id']."'");
					}
					if($to_info['parent_id'] > 0){						DB::query("UPDATE ".DB::table('channel')." SET total_topic_num=total_topic_num+{$from_info['total_topic_num']} WHERE ch_id = '".$to_info['parent_id']."'");
					}
				}
				if($cutc){
					DB::query("DELETE FROM ".DB::table('channel')." WHERE ch_id='{$from_id}'");
				}
				$this->update_category_cache();
			}
			return 1;
		}else{
			return 0;
		}
	}

	
	function category_tree($data, $parent_id = 0)
	{
		$tree = array();
		foreach ($data as $value) {
			if ($value['parent_id'] == $parent_id) {
				$tmp = array();
				$tmp = $value;
				$tmp['child'] = $this->category_tree($data, $value['ch_id']);
				$tree[$value['ch_id']] = $tmp;
			}
		}
		return $tree;
	}

	
	function add_category($ch_name, $display_order = 0, $parent_id = 0)
	{
		$set_ary = array(
			'ch_name' => $ch_name,
			'parent_id' => $parent_id,
			'display_order' => $display_order,
		);
		$cid = DB::insert('channel', $set_ary, true);
		return $cid;
	}

	
	function update_category($ch_id, $ch_name, $display_order)
	{
		$set_ary = array(
			'ch_name' => $ch_name,
			'display_order' => $display_order,
		);
		DB::update('channel', $set_ary, array('ch_id' => $ch_id));
	}

	
	function delete_category($ch_id)
	{
				$category = $this->id2category($ch_id);
		if (empty($category)) {
			return -1;
		}

		if ($category['topic_num'] > 0) {
			return -2;
		}

				$sub_count = DB::result_first("SELECT COUNT(*)
									   FROM ".DB::table('channel')."
									   WHERE parent_id='{$ch_id}'");
		if ($sub_count) {
			return -3;
		}

		DB::query("DELETE FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
		DB::query("DELETE FROM ".DB::table('buddy_channel')." WHERE ch_id='{$ch_id}'");
		return 1;
	}

	
	function update_category_cache()
	{
		$cat_ary = array(); $channles = array();
		$query = DB::query("SELECT * FROM ".DB::table('channel')." ORDER BY display_order ASC");
		while ($value = DB::fetch($query)) {
			$channles[$value['ch_id']][$value['ch_id']] = $value['ch_id'];
			if ($value['parent_id'] == 0) {
				$cat_ary['first'][$value['ch_id']] = $value;
			} else {
				$cat_ary['second'][$value['ch_id']] = $value;
				$channles[$value['parent_id']][$value['ch_id']] = $value['ch_id'];
			}
		}
		$cat_ary['channels'] = $channles;
		ConfigHandler::set('channel', $cat_ary);
	}

	
	function get_category()
	{
		$cat_ary = array();
		$cat_ary = ConfigHandler::get('channel');
		if (empty($cat_ary)) {
			$cat_ary = $this->update_category_cache();
		}
		return $cat_ary;
	}
	function get_pub_channel()
	{
		global $_J;
		$channels = array();
		$cachefile = $this->get_category();
		$channel_enable = $cachefile && $cachefile['channels'] ? true : false;
		if($cachefile){
			$channel_one = is_array($cachefile['first']) ? $cachefile['first'] : array();
			foreach($channel_one as $key => $val){
				if(empty($val['purview']) || ($val['purview'] && in_array($_J['member']['role_id'],explode(',',$val['purview'])))){$val['ok'] = true;}else{$val['ok'] = false;}
				if($val['verify'] && !in_array($_J['member']['role_id'],explode(',',$val['filter']))){$val['ck'] = 1;}else{$val['ck'] = 0;}
				$channels[$key] = $val;
			}
			$channel_two = is_array($cachefile['second']) ? $cachefile['second'] : array();
			foreach($channel_two as $k => $v){
				if(empty($v['purview']) || ($v['purview'] && in_array($_J['member']['role_id'],explode(',',$v['purview'])))){$v['ok'] = true;}else{$v['ok'] = false;}
				if($v['verify'] && !in_array($_J['member']['role_id'],explode(',',$v['filter']))){$v['ck'] = 1;}else{$v['ck'] = 0;}
				$channels[$v['parent_id']]['child'][$k] = $v;
			}
		}
		return array('channel_enable'=>$channel_enable,'channels'=>$channels);
	}
	function get_select_channel()
	{
		global $_J;
		$channels = array();
		$cachefile = $this->get_category();
		$channel_one = is_array($cachefile['first']) ? $cachefile['first'] : array();
		$channel_two = is_array($cachefile['second']) ? $cachefile['second'] : array();
		foreach($channel_one as $key => $val){
			if(!empty($val['purview']) && !in_array($_J['member']['role_id'],explode(',',$val['purview']))){
				$val['disabled'] = true;
			}
			$channels[$key] = $val;
			foreach($channel_two as $k => $v){
				if($v['parent_id'] == $key){
					if(!empty($v['purview']) && !in_array($_J['member']['role_id'],explode(',',$v['purview']))){
						$v['disabled'] = true;
					}
					$v['ch_name'] = '&nbsp;&nbsp;'.$v['ch_name'];
					$channels[$k] = $v;
				}
			}
		}
		return $channels;
	}

	
	function get_catselect($id = 0)
	{
		$html = '';
		$cat_ary = $this->get_category();
		if (!empty($cat_ary)) {
			$first_cat = $cat_ary['first'];
			foreach ($first_cat as $value) {
				$ps = '';
				if ($value['ch_id'] == $id) {
					$ps = ' selected="selected"';
				}
				$html .= '<option value="'.$value['ch_id'].'"'.$ps.'>'.$value['ch_name'].'</option>';
			}
			$html = '<select name="parent_id">'.$html.'</select>';
		}
		return $html;
	}

	
	function upload_pic($id){

		$image_name = $id.".png";
		$image_path = RELATIVE_ROOT_PATH . 'images/channel/'.face_path($id);
		$image_file = $image_path . $image_name;

		if (!is_dir($image_path))
		{
			jlib('io')->MakeDir($image_path);
		}
		Load::lib('upload');
		$UploadHandler = new UploadHandler($image_path,'image',true);
		$UploadHandler->setMaxSize(1000);
		$UploadHandler->setNewName($image_name);
		$result=$UploadHandler->doUpload();

		if($result)
        {
			$result = is_image($image_file);
		}
		if(!$result)
        {
			unlink($image_file);
			return false;
		}else{
			if($GLOBALS['_J']['config']['ftp_on']) {
	            $ftp_key = randgetftp();
				$get_ftps = ConfigHandler::get('ftp');
	            $site_url = $get_ftps[$ftp_key]['attachurl'];
	            $ftp_result = ftpcmd('upload',$image_file,'',$ftp_key);
	            if($ftp_result > 0) {
	                jlib('io')->DeleteFile($image_file);
	                $image_file = $site_url .'/'. str_replace('./','',$image_file);
	            }
	        }
			DB::update('channel', array('picture' => $image_file), array('ch_id' => $id));
		}
		return true;
	}

    
    function getChannelUser($channel,$limit=100){
        $uid = array();
        if (!$channel) {
            return $uid;
        } else if (is_array($channel)) {
            $where = " where `ch_id` in (".  jimplode($channel).")";
        } else {
            $channel = (int) $channel;
            $where = " where `ch_id` = '$channel' ";
        }
        $sql = " select `uid` from `".DB::table('buddy_channel')."` $where limit $limit ";

        $query = DB::query($sql);
        while ($rs = DB::fetch($query)) {
            $uid[$rs['uid']] = $rs['uid'];
        }
        return $uid;
    }

	

	function getThisChannel($ch_id=0){
		$channel = DB::fetch_first("SELECT * FROM ".DB::table('channel')." WHERE ch_id='{$ch_id}'");
		$return = array('name'=>'频道不存在','list'=>'txt','view'=>'post');
		$navhtml = '<a href="'.jurl('index.php?mod=channel').'" class="navLefthome">频道首页</a>';
		if($channel){
			if($channel['parent_id'] > 0){
				$channelp = DB::fetch_first("SELECT ch_name FROM ".DB::table('channel')." WHERE ch_id='{$channel['parent_id']}'");
				$navhtml .= $channelp ? '<a href="'.jurl('index.php?mod=channel&id='.$channel['parent_id']).'" class="navLeftsub">'.$channelp['ch_name'].'</a>' : '';
				$navhtml .= '<a href="'.jurl('index.php?mod=channel&id='.$channel['ch_id']).'" class="navLeftsub2 subon">'.$channel['ch_name'].'</a>';
			}else{
				$navhtml .= '<a href="'.jurl('index.php?mod=channel&id='.$channel['ch_id']).'" class="navLeftsub subon">'.$channel['ch_name'].'</a>';
			}
			$buddy_mumbers = $this->getChannelBuddyUserNums($channel['ch_id']);
			$my_channels = $this->mychannel();
			$my_channels_key = array_keys($my_channels);
			$channel_buddy = follow_channel($channel['ch_id'],in_array($channel['ch_id'],$my_channels_key));
			$navhtml .= '<span id="follow_channel" class="follow_c_'.$channel['ch_id'].'">'.$channel_buddy.'</span>';
			$navhtml .= '<div class="navinfo"><span>关注：<font class="follow_num_'.$channel['ch_id'].'">'.$buddy_mumbers.'</font>人</span><span>内容：'.$channel['total_topic_num'].'条</span></div>';
			$return['description'] = $channel['description'];
			$return['name'] = $channel['ch_name'];
			$return['list'] = $channel['display_list'];
			$return['view'] = $channel['display_view'];
		}
		$return['navhtml'] = $navhtml;
		return $return;
	}


	

	function getChannelBuddyUserNums($ch_id=0){
		$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('buddy_channel')." WHERE ch_id='{$ch_id}'");
		return $count;
	}

	

	function getChannelRecTopic(){
		$rtopic = array();
		$sql = "SELECT r.tid,r.item_id,r.r_title,c.ch_name FROM ".DB::table('topic_recommend')." AS r LEFT JOIN ".DB::table('channel')." AS c ON r.item_id = c.ch_id WHERE r.item = 'channel' AND r.r_title <> '' AND (r.expiration>".time()." OR r.expiration=0) ORDER BY r.dateline DESC LIMIT 12";
        $query = DB::query($sql);
        while ($rs = DB::fetch($query)) {
            $rtopic[] = $rs;
        }
		return $rtopic;
	}
	function getChannelTopTopic(){
		$ttopic = array();
		$sql = "SELECT r.tid,t.content,t.content2 FROM ".DB::table('topic_recommend')." AS r LEFT JOIN ".DB::table('topic')." AS t ON r.tid = t.tid WHERE r.item = 'channel' AND r.recd = 4 AND (r.expiration>".time()." OR r.expiration=0) ORDER BY r.dateline DESC LIMIT 1";
		$query = DB::query($sql);
		while ($rs = DB::fetch($query)) {
            $ttopic = $rs;
        }
		if($ttopic){
			$ttopic['content'] .= $ttopic['content2'];
			unset($ttopic['content2']);
			$ttopic['content'] = jhtmlspecialchars(strip_tags($ttopic['content']));
			if(false !== strpos($ttopic['content'], 'http:/'.'/')) {
				$ttopic['content'] = preg_replace('~(http:/'.'/[a-z0-9-\.\?\=&;_@/%#]+?)\s+~i', '<a href="\\1" target="_blank">Click Here</a> ', $ttopic['content']);
				$ttopic['content'] = preg_replace("|\s*http:/"."/[a-z0-9-\.\?\=&;_@/%#]*\$|sim", "", $ttopic['content']);
			}
		}
		return $ttopic;
	}

	
	function getChannelAll(){
		$channles = array();
		$my_channels = $this->mychannel();
		$my_channels_key = array_keys($my_channels);
		$query = DB::query("SELECT ch_id,ch_name,topic_num,total_topic_num,parent_id,picture FROM ".DB::table('channel')." ORDER BY parent_id ASC,display_order ASC");
		while ($value = DB::fetch($query)) {
			$parent_id = $value['parent_id'];
			$value['buddy_mumbers'] = $this->getChannelBuddyUserNums($value['ch_id']);
			$value['picture'] = $value['picture'] ? $value['picture'] : './images/channelimg.gif';
			unset($value['parent_id']);
			if($value['total_topic_num'] > $value['topic_num']){
				$value['topic_num'] = $value['total_topic_num'];
			}
			unset($value['total_topic_num']);
			$value['channel_buddy'] = follow_channel($value['ch_id'],in_array($value['ch_id'],$my_channels_key));
			if ($parent_id == 0) {
				$channles[$value['ch_id']] = $value;
			} else {
				$channles[$parent_id]['child'][$value['ch_id']] = $value;
			}
		}
		return $channles;
	}

	
	function getUserFansTop(){
		$users = array();
		$query = DB::query("SELECT uid,username,nickname FROM ".DB::table('members')." ORDER BY fans_count DESC LIMIT 12");
		while ($value = DB::fetch($query)) {
			$value['face'] = face_get($value['uid']);
			$users[] = $value;
		}
		return $users;
	}
	
	function getLastUser(){
		$users = array();
		$query = DB::query("SELECT uid,username,nickname FROM ".DB::table('members')." ORDER BY uid DESC LIMIT 12");
		while ($value = DB::fetch($query)) {
			$value['face'] = face_get($value['uid']);
			$users[] = $value;
		}
		return $users;
	}

	
	function get_two_new_topic($channel_ids,$num=2){
		$tids = $topic_list = $c_tids = $channel_topic = array();
		$query = DB::query("SELECT ch_name FROM ".DB::table('channel')." WHERE ch_id IN(".implode(",",$channel_ids).") ORDER BY ch_id");
		while ($value = DB::fetch($query)) {
			$channel_topic[$value['ch_name']] = array();
		}
		$sql = "SELECT a.tid, c.ch_name FROM ".DB::table('topic_channel')." a LEFT JOIN ".DB::table('topic_channel')." b ON a.item_id=b.item_id AND a.tid<b.tid LEFT JOIN ".DB::table('channel')." c ON a.item_id=c.ch_id  WHERE a.item_id IN(".implode(",",$channel_ids).") GROUP BY a.item_id,a.tid HAVING COUNT(b.tid)<'".$num."' ORDER BY a.item_id,a.tid";
		$query = DB::query($sql);
		while ($value = DB::fetch($query)) {
			$c_tids[$value['ch_name']][] = $value['tid'];
			$tids[] = $value['tid'];
		}
		$options = array('tid'=>$tids,'count'=>'20','order'=>'dateline DESC');
		$TopicListLogic = jlogic('topic_list');
		$info = $TopicListLogic->get_data($options);
		$topic_list = $info['list'];
		foreach($c_tids as $key => $val){
			foreach($val as $v){
				if($topic_list[$v]){
					$channel_topic[$key][$v] = $topic_list[$v];
					$channel_topic[$key][$v]['content'] = cut_str(strip_tags($topic_list[$v]['content']),80);
				}
			}
		}
		unset($tids);unset($topic_list);unset($c_tids);
		return $channel_topic;
	}

	
	function get_child_channel($channel_id = 0){
		$channels = array();
		$query = DB::query("SELECT * FROM ".DB::table('channel')." WHERE parent_id = '".$channel_id."'ORDER BY ch_id ASC");
		while ($value = DB::fetch($query)) {
			$channels[] = $value;
		}
		return $channels;
	}
}
?>